package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.dto.ChannelDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.mapper.WmChannelMapper;
import com.heima.media.service.IWmChannelService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

@Service
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements IWmChannelService {

    @Override
    public ResponseResult listByName(ChannelDto dto) {
        // 根据名称分页查询频道列表
        // 构建查询条件
        LambdaQueryWrapper<WmChannel> query = new LambdaQueryWrapper<>();
        //判断name是否存在
        if (!StringUtils.isEmpty(dto.getName())){
            query.like(WmChannel::getName,dto.getName());
        }
        //构建分页条件
        IPage<WmChannel> page = new Page<>(dto.getPage(), dto.getSize());
        IPage<WmChannel> iPage = this.page(page,query);

        ResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), iPage.getTotal(), iPage.getRecords());

        return result;
    }


    @Override
    public ResponseResult saveChannel(WmChannel channel) {
        // 保存新的频道,判断频道名称是否已经存在,已经存在不再新增
        // 检查参数
        if (channel==null || StringUtils.isEmpty(channel)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //根据频道名称查询表记录
        LambdaQueryWrapper<WmChannel> query = new LambdaQueryWrapper<>();
        query.eq(WmChannel::getName,channel.getName());
        int count = this.count(query);
        //如果大于0已经存在
        if (count>0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
        //不存在则添加
        channel.setCreatedTime(new Date());
        this.save(channel);

        return ResponseResult.okResult(channel.getId());
    }
}
